<?php


namespace app\shop\controller\pc;

use app\Request;
use app\shop\model\user\FriendModel;
use app\shop\model\user\UserModel;
use app\shop\model\user\SmsModel;

use app\BaseController;
use app\shop\service\user\UserService;
use app\shop\validate\UserValidate;
use think\Validate;

class UserController extends BaseController
{
    //   用户信息查询
    public function UserInfo()
    {
        try {
            $userInfo = $this->request->middleware('userInfo');
            unset($userInfo['password']);
            return $this->success($userInfo);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

    /**
     * 用户信息修改 附带密码修改
     */
    public function setUserInfo()
    {
        try {
            // 昵称
            $realname = $this->request->param('realname', '', 'trim');
            // 手机号
            $mobile = $this->request->param('mobile', '', 'trim');
            $pwd = $this->request->param('password', '', 'trim');
            $userInfo = $this->request->middleware('userInfo');
            // 用户分类
            $user_classification = $userInfo->role_id;

            // 如果用户分类为 3 或 4，则限制昵称长度
            if ($user_classification == 3 || $user_classification == 4) {
                // 假设昵称最大长度为 20
                if (mb_strlen($realname) > 20) {
                    return $this->error('昵称长度不能超过20个字符');
                }
            }

            // 检查昵称不能是手机号格式
            if (preg_match('/^1\d{10}$/', $realname)) {
                return $this->error('昵称不能为手机号格式');
            }

            $userInfo->mobile = $mobile;
            $userInfo->realname = $realname;
            if ($pwd) {
                $userInfo->password = password_hash($pwd . $userInfo->salt, PASSWORD_DEFAULT);
            }

            // 头像上传处理
            $file = $this->request->file('avatar');
            if ($file) {
                // 移动到 public 目录下的 avatars 文件夹
                $avatarPath = $file->move('avatars');
                $userInfo->avatar = '/storage/' . $avatarPath->getSaveName(); // 设置用户的头像路径，假设是 public/storage/avatars/filename
            }

            $userInfo->save();
            return $this->success();
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }

  

    /**
     * 登录
     * @return \think\response\Json
     */
    public function login()
    {
        try {
            $data = $this->request->only(['mobile', 'password']);

            Validate(UserValidate::class)->scene('login')->check($data);

            // 使用模型查询用户信息
            $userInfo = UserModel::where('mobile', $data['mobile'])->find();
            if (!$userInfo) {
                throw new \Exception('账号错误');
            }

            // 密码不匹配
            if (!password_verify($data['password'] . $userInfo->salt, $userInfo->password)) {
                throw new \Exception('密码错误');
            }

            // 更新用户登录信息和生成token
            $token = 'PC|' . random(30, 'string');
            $info = [
                'last_login_time' => time(),
                'last_login_ip' => $this->request->ip(),
                'pc_token' => $token,
                'login_status' => 1,
                'pc_token_valid_time' => time() + 86400,
            ];

            $userInfo->save($info);
            // 返回结果
            unset($userInfo['password']);
            $userInfo['token'] = $token;
            return $this->success($userInfo);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }



    // //验证短信验证码  暂时不用
    // public function shortMessage(){
    //     try {
    //     $code = $this->request->param('code'); // 获取验证码
    //     $user_id = $this->request->userId;
    //     $mobile = UserModel::where('id', $user_id)->value('mobile');// 获取手机号
    //     if(!$mobile || $mobile <= ""){
    //             throw new Exception('手机号不存在');
    //         }
    //     // 验证短信验证码是否正确
    //     $sms = SmsModel::where('mobile', $mobile)
    //                   ->where('code', $code)
    //                   ->order('create_time', 'desc') // 假设按照创建时间倒序，取最新的验证码记录
    //                   ->find();

    //     if (!$sms) {
    //         throw new Exception('验证码错误或已过期');
    //     }
    //   // 验证验证码是否过期
    //     $validTime = strtotime($sms->valid_time); //验证码过期时间
    //     if (time() > $validTime) {
    //         throw new Exception('验证码已过期');
    //     }   
    //     return $this->success('验证码验证通过');

    // } catch (Exception $exception) {
    //     // 捕获异常并返回错误消息
    //     return $this->error($exception->getMessage());
    // }
    // }

    // 获取联系人列表
    public function getContacts()
    {
        try {
            $data = UserService::getUserList([['status', '=', 1], ['user_id', '<>', $this->userInfo['user_id']]], $this->userInfo['user_id']);
            $count = FriendModel::where(['status' => 2, 'friend_user_id' => $this->uid])->count();
            $time = FriendModel::where(['friend_user_id' => $this->uid, 'is_invite' => 1])->order('create_time desc')->value('create_time');
            return $this->success(['data' => $data, 'count' => $count, 'time' => $time]);
        } catch (\Exception $exception) {
            return $this->error($exception->getMessage());
        }
    }
}